//
//  CWCMilitaryViewController.m
//  ChuanNews
//
//  Created by dllo on 16/4/21.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CWCMilitaryViewController.h"
#import "BaseHeader.h"
@interface CWCMilitaryViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, retain)NSTimer *outTimer;
@property(nonatomic, retain)UIImageView *imgView;
@property(nonatomic, retain)UILabel *titleLabel;
@property(nonatomic, assign)int page;

@end

@implementation CWCMilitaryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.array = [NSMutableArray array];
    self.oneArray = [NSMutableArray array];
    self.tableView = [[ UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView release];
    
    
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
        if (_outTimer) {
            [_outTimer invalidate];
            _outTimer = nil;
        }
        self.outTimer = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(showNetWorkBad) userInfo:nil repeats:NO];
        [self creatData];
    }];
    [self.tableView.mj_header beginRefreshing];
    self.page = 1;
    [self setupFooter];
    
    [self setupHeadView];
    [self.tableView registerClass:[CostomCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[CWCImageCell class] forCellReuseIdentifier:@"Cell"];
    
}

-(void)setupFooter{
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self refreshFooterView];
    }];
}

-(void)refreshFooterView{
    NSString *pageCount = [NSString stringWithFormat:@"%d-%d", 20 + (self.page - 1) * 20 ,20];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:[NSString stringWithFormat:@"http://c.m.163.com/nc/article/list/T1348648141035/%@.html",pageCount] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dic = responseObject;
        NSArray *Array = dic[@"T1348648141035"];
        for (NSDictionary *dic in Array) {
            if (dic[@"imgextra"] == nil) {
                CWCDataModel *model = [[CWCDataModel alloc]initWithDic:dic];
                [self.array addObject:model];
                [model release];
            }else{
                CWCDataModel *model = [[CWCDataModel alloc]initWithDic:dic];
                NSArray *imgArray = dic[@"imgextra"];
                NSDictionary *imgDic1 = imgArray[0];
                NSString *urlImage1 = imgDic1[@"imgsrc"];
                [model setValue:urlImage1 forKey:@"imgsrc1"];
                NSDictionary *imgDic2 = imgArray[1];
                NSString *urlImage2 = imgDic2[@"imgsrc"];
                [model setValue:urlImage2 forKey:@"imgsrc2"];
                [self.array addObject:model];
                [model release];
            }
        }
        [self.tableView reloadData];
        self.page++;
        [self.tableView.mj_footer setState:MJRefreshStateIdle];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        
    }];
    
    
}
-(void)showNetWorkBad{
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您当前的网络不给力，请重新刷新！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    if (_outTimer) {
        [_outTimer invalidate];
        _outTimer = nil;
    }
    [self.tableView.mj_header endRefreshing];
}

-(void)creatData{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:@"http://c.m.163.com/nc/article/list/T1348648141035/0-20.html" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.array removeAllObjects];
        NSDictionary * dic = responseObject;
        NSArray *Array = dic[@"T1348648141035"];
        for (NSDictionary *dic in Array) {
            if (dic[@"imgextra"] == nil) {
                CWCDataModel *model = [[CWCDataModel alloc]initWithDic:dic];
                [self.array addObject:model];
            }else{
                CWCDataModel *model = [[CWCDataModel alloc]initWithDic:dic];
                NSArray *imgArray = dic[@"imgextra"];
                NSDictionary *imgDic1 = imgArray[0];
                NSString *urlImage1 = imgDic1[@"imgsrc"];
                [model setValue:urlImage1 forKey:@"imgsrc1"];
                NSDictionary *imgDic2 = imgArray[1];
                NSString *urlImage2 = imgDic2[@"imgsrc"];
                [model setValue:urlImage2 forKey:@"imgsrc2"];
                [self.array addObject:model];
            }
        }
        
        CWCDataModel * model = self.array[0];
        [self.oneArray addObject:model];
        
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
        self.titleLabel.text = model.title;
        [self.array removeObjectAtIndex:0];
        
        [self.tableView.mj_header endRefreshing];
        if (self.outTimer) {
            [self.outTimer invalidate];
            self.outTimer = nil;
        }
        
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
}

-(void)setupHeadView{
    self.imgView = [[ UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    self.imgView.clipsToBounds = YES;
    self.imgView.contentMode = UIViewContentModeScaleAspectFill;
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 180, WIDTH - 5, 20)];
    self.titleLabel.font = [UIFont systemFontOfSize:14];
    self.titleLabel.textColor = [UIColor whiteColor];
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, WIDTH, 200);
    button.backgroundColor = [UIColor clearColor];
    [button addTarget:self action:@selector(pushDetailView:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.imgView];
    [headView addSubview:self.titleLabel];
    [self.imgView release];
    [self.titleLabel release];
    [headView addSubview:button];
    self.tableView.tableHeaderView = headView;
    [headView release];
}
-(void)pushDetailView:(UIButton *)button{
    CWCDataModel *model = self.oneArray[0];
    if (!model.photosetID) {
        CWCDetailReadingViewController *vc = [[CWCDetailReadingViewController alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.id = model.docid;
        
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }else{
        CWCPhotoDetailViewController *vc = [[CWCPhotoDetailViewController alloc]init];
        vc.setid = model.photosetID;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CWCDataModel *model = self.array[indexPath.row];
    if (model.imgextra == nil) {
        CostomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        NSURL *url = [NSURL URLWithString:model.imgsrc];
        [cell.imgView sd_setImageWithURL:url];
        cell.titleLabel.text = model.title;
        cell.titleLabel.font = [UIFont systemFontOfSize:18];
        cell.digestLabel.text = model.digest;
        cell.digestLabel.font = [UIFont systemFontOfSize:14];
        return cell;
    }else {
        CWCImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
        [cell.imgView1 sd_setImageWithURL:[NSURL URLWithString:model.imgsrc1]];
        [cell.imgView2 sd_setImageWithURL:[NSURL URLWithString:model.imgsrc2]];
        cell.titleLabel.text = model.title;
        cell.titleLabel.font = [UIFont systemFontOfSize:16];
        return cell;
    }
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CWCDataModel *model = self.array[indexPath.row];
    if (!model.photosetID) {
        CWCDetailReadingViewController *vc = [[CWCDetailReadingViewController alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.id = model.docid;
        
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }else{
        CWCPhotoDetailViewController *vc = [[CWCPhotoDetailViewController alloc]init];
        vc.setid = model.photosetID;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }
}

-(void)dealloc {
    [_outTimer release];
    [_tableView release];
    [_imgView release];
    [_titleLabel release];
    [super dealloc];
}
    
    
    
    
    
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
